package com.example.carbonbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.carbonbackend.common.BaseResponse;
import com.example.carbonbackend.common.ErrorCode;
import com.example.carbonbackend.common.ResultUtils;
import com.example.carbonbackend.exception.BusinessException;
import com.example.carbonbackend.exception.ThrowUtils;
import com.example.carbonbackend.model.dto.trade.TradeAddRequest;
import com.example.carbonbackend.model.dto.trade.TradeQueryRequest;
import com.example.carbonbackend.model.entity.CompanyUser;
import com.example.carbonbackend.model.entity.Trade;
import com.example.carbonbackend.model.entity.User;
import com.example.carbonbackend.model.vo.TradeVO;
import com.example.carbonbackend.service.CompanyUserService;
import com.example.carbonbackend.service.TradeService;
import com.example.carbonbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("trade")
@Slf4j
public class TradeController {

    @Resource
    private TradeService tradeService;

    @Resource
    private UserService userService;

    @Resource
    private CompanyUserService companyUserService;

    // region 增删改查

    /**
     * 创建
     *
     * @param tradeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTrade(@RequestBody TradeAddRequest tradeAddRequest, HttpServletRequest request) {
        // 设置卖方、买方
        User loginUser = userService.getLoginUser(request);
        tradeAddRequest.setBuyerId(loginUser.getId());
        Long companyId = tradeAddRequest.getCompanyId();
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        CompanyUser one = companyUserService.getOne(queryWrapper);
        tradeAddRequest.setSellerId(one.getUserId());
        tradeAddRequest.setTradeTime(new Date());
        // 判断是否添加记录
        if (tradeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Trade trade = new Trade();
        BeanUtils.copyProperties(tradeAddRequest, trade);

        boolean save = tradeService.save(trade);

        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(trade.getBuyerId());

    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TradeVO> getTradeVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Trade trade = tradeService.getById(id);
        if (trade == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(tradeService.getTradeVO(trade, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param tradeQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Trade>> listTradeByPage(@RequestBody TradeQueryRequest tradeQueryRequest) {
        long current = tradeQueryRequest.getCurrent();
        long size = tradeQueryRequest.getPageSize();
        Page<Trade> tradePage = tradeService.page(new Page<>(current, size),
                tradeService.getQueryWrapper(tradeQueryRequest));
        return ResultUtils.success(tradePage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param tradeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TradeVO>> listTradeVOByPage(@RequestBody TradeQueryRequest tradeQueryRequest,
                                                         HttpServletRequest request) {
        long current = tradeQueryRequest.getCurrent();
        long size = tradeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Trade> tradePage = tradeService.page(new Page<>(current, size),
                tradeService.getQueryWrapper(tradeQueryRequest));
        return ResultUtils.success(tradeService.getTradeVOPage(tradePage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param tradeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TradeVO>> listMyTradeVOByPage(@RequestBody TradeQueryRequest tradeQueryRequest,
                                                           HttpServletRequest request) {
        log.info("查询信息{}", tradeQueryRequest);
        if (tradeQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        tradeQueryRequest.setBuyerId(loginUser.getId());
        long current = tradeQueryRequest.getCurrent();
        long size = tradeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Trade> tradePage = tradeService.page(new Page<>(current, size),
                tradeService.getQueryWrapper(tradeQueryRequest));

        return ResultUtils.success(tradeService.getTradeVOPage(tradePage, request));
    }


}
